/*
 *  Copyright 2009 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.mybatis.generator.codegen.mybatis3.service;

import static org.mybatis.generator.internal.util.StringUtility.stringHasValue;
import static org.mybatis.generator.internal.util.messages.Messages.getString;

import java.util.ArrayList;
import java.util.List;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.AbstractJavaClientGenerator;
import org.mybatis.generator.codegen.AbstractXmlGenerator;
import org.mybatis.generator.codegen.mybatis3.service.elements.AbstractJavaServiceMethodGenerator;
import org.mybatis.generator.codegen.mybatis3.service.elements.DeleteByPrimaryKeyMethodOfServiceGenerator;
import org.mybatis.generator.codegen.mybatis3.service.elements.FindByConditionMethodOfServiceGenerator;
import org.mybatis.generator.codegen.mybatis3.service.elements.FindListMethodOfService;
import org.mybatis.generator.codegen.mybatis3.service.elements.InsertMethodOfServiceGenerator;
import org.mybatis.generator.codegen.mybatis3.service.elements.SelectByPrimaryKeyMethodOfServiceGenerator;
import org.mybatis.generator.codegen.mybatis3.service.elements.UpdateByPrimaryKeySelectiveMethodOfServiceGenerator;
import org.mybatis.generator.codegen.mybatis3.xmlmapper.XMLMapperGenerator;
import org.mybatis.generator.config.PropertyRegistry;


/**
 * service构造类
 *
 * @author tangdelong
 * 2015年5月22日
 */
public class JavaServiceGenerator extends AbstractJavaClientGenerator {

    /**
     * 
     */
    public JavaServiceGenerator() {
        super(true);
    }

    public JavaServiceGenerator(boolean requiresMatchedXMLGenerator) {
        super(requiresMatchedXMLGenerator);
    }
    
    @Override
    public List<CompilationUnit> getCompilationUnits() {
    	progressCallback.startTask(getString("Progress.17", //$NON-NLS-1$
                introspectedTable.getFullyQualifiedTable().toString()));
        CommentGenerator commentGenerator = context.getCommentGenerator();

        FullyQualifiedJavaType parentType = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
        
        FullyQualifiedJavaType type = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaServiceType());
        TopLevelClass topLevelClass = new TopLevelClass(type);
        // 类加注解
        List<String> classAnnotationLs = new ArrayList<String>();
        classAnnotationLs.add("Service");
        topLevelClass.setAnnotationNames(classAnnotationLs);
        topLevelClass.addImportedType("org.springframework.stereotype.Service");
        topLevelClass.addImportedType("org.springframework.transaction.annotation.Transactional");
        
        topLevelClass.setVisibility(JavaVisibility.PUBLIC);
        commentGenerator.addJavaFileComment(topLevelClass);
        
        // 类加注释
        commentGenerator.addClassComment(topLevelClass, introspectedTable,"service");

        String rootInterface = introspectedTable
            .getTableConfigurationProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
        if (!stringHasValue(rootInterface)) {
            rootInterface = context.getJavaClientGeneratorConfiguration()
                .getProperty(PropertyRegistry.ANY_ROOT_INTERFACE);
        }

        
        
        
        // 获取Mapper类
        FullyQualifiedJavaType mapper = new FullyQualifiedJavaType(
                introspectedTable.getMyBatis3JavaMapperType());
        
        // 注入Mapper
        Field field = new Field();
        field.setVisibility(JavaVisibility.PRIVATE);
        field.setType(mapper);
        field.setName(mapper.getInjectName());
        List<String> strLs = new ArrayList<String>();
        strLs.add("Autowired");
        field.setAnnotationNames(strLs);
        topLevelClass.addImportedType("org.springframework.beans.factory.annotation.Autowired");
        
        topLevelClass.addField(field);
        topLevelClass.addImportedType(mapper);
        
        // 方法添加
        addInsertSelectiveMethod(topLevelClass);
        addDeleteByPrimaryKeyMethod(topLevelClass);
        addUpdateByPrimaryKeySelectiveMethod(topLevelClass);
        addSelectByPrimaryKeyMethod(topLevelClass);
        addFindByConditionMethod(topLevelClass);
        addFindListMethod(topLevelClass);
        

       

        List<CompilationUnit> answer = new ArrayList<CompilationUnit>();
//        if (context.getPlugins().clientGenerated(topLevelClass, null,
//                introspectedTable)) {
//            answer.add(topLevelClass);
//        }
//        
        answer.add(topLevelClass);
        
        List<CompilationUnit> extraCompilationUnits = getExtraCompilationUnits();
        if (extraCompilationUnits != null) {
            answer.addAll(extraCompilationUnits);
        }

        return answer;
    }

    protected void addDeleteByPrimaryKeyMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateDeleteByPrimaryKey()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new DeleteByPrimaryKeyMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }

    protected void addInsertMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateInsert()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new InsertMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }

    protected void addInsertSelectiveMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateInsertSelective()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new InsertMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }
    
    /**
     * 新增：根据条件查询
     *
     * @author tangdelong
     * 2015年5月15日
     */
    protected void addFindByConditionMethod(TopLevelClass topLevelClass){
    	AbstractJavaServiceMethodGenerator methodGenerator = new FindByConditionMethodOfServiceGenerator();
         initializeAndExecuteGenerator(methodGenerator, topLevelClass);
    }
    
    /**
     * 新增：根据条件查询
     *
     * @author tangdelong
     * 2015年5月15日
     */
    protected void addFindListMethod(TopLevelClass topLevelClass){
    	AbstractJavaServiceMethodGenerator methodGenerator = new FindListMethodOfService();
    	initializeAndExecuteGenerator(methodGenerator, topLevelClass);
    }


    protected void addSelectByPrimaryKeyMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateSelectByPrimaryKey()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new SelectByPrimaryKeyMethodOfServiceGenerator(false);
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }


    protected void addUpdateByPrimaryKeySelectiveMethod(TopLevelClass topLevelClass) {
        if (introspectedTable.getRules().generateUpdateByPrimaryKeySelective()) {
        	AbstractJavaServiceMethodGenerator methodGenerator = new UpdateByPrimaryKeySelectiveMethodOfServiceGenerator();
            initializeAndExecuteGenerator(methodGenerator, topLevelClass);
        }
    }



    protected void initializeAndExecuteGenerator(
    		AbstractJavaServiceMethodGenerator methodGenerator,
            TopLevelClass topLevelClass) {
        methodGenerator.setContext(context);
        methodGenerator.setIntrospectedTable(introspectedTable);
        methodGenerator.setProgressCallback(progressCallback);
        methodGenerator.setWarnings(warnings);
        methodGenerator.addServiceElements(topLevelClass);
    }

    public List<CompilationUnit> getExtraCompilationUnits() {
        return null;
    }

    @Override
    public AbstractXmlGenerator getMatchedXMLGenerator() {
        return new XMLMapperGenerator();
    }
}
